package com.quasar.hpatient.dialog;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import com.quasar.hpatient.R;

import lib.quasar.base.dialog.BaseDialog;

/**
 * description: 输入框编辑
 * created by kalu on 2018/3/29 9:03
 */
public class EditDialog extends BaseDialog implements View.OnClickListener {

    private final String tempStr = String.valueOf(-1);

    private String editStr = tempStr;
    private String editDefault = "";
    /************************************************/

    private OnDialogChangeListener listener;

    public EditDialog(Activity activity) {
        super(activity);
    }

    @Override
    public void show() {
        super.show();
        setCanceledOnTouchOutside(false);
        setCancelable(false);
    }

    @Override
    public void dismiss() {

        if (null != listener && !tempStr.equals(editStr)) {
            listener.onEditChange(editStr);
        }

        super.dismiss();
    }

    @Override
    public void cancel() {

        if (null != listener && !tempStr.equals(editStr)) {
            listener.onEditChange(editStr);
        }

        super.cancel();
    }

    @Override
    protected int initView() {
        return R.layout.layout_dialog_edit;
    }

    @Override
    protected void initData() {

        findViewById(R.id.layout_dialog_edit_back).setOnClickListener(this);
        findViewById(R.id.layout_dialog_edit_ok).setOnClickListener(this);

        final EditText edit = findViewById(R.id.layout_dialog_edit_input);
        if (null == edit) return;

        edit.setText(editDefault);
        edit.setSelection(editDefault.length());
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                final String trim = edit.getText().toString().trim();
                editStr = trim;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_dialog_edit_back:
                editStr = tempStr;
                dismiss();
                break;
            case R.id.layout_dialog_edit_ok:
                dismiss();
                break;
        }
    }

    public void setEditInput(String str) {
        editDefault = str;
    }

    public void setOnDialogChangeListener(OnDialogChangeListener mListener) {
        this.listener = mListener;
    }

    public interface OnDialogChangeListener {
        void onEditChange(String edit);
    }
}
